#!/usr/bin/env python
# -*- coding: utf-8 -*-
import datetime
import time
from model.mysql_model import MysqlElephantV2, MysqlCompareV2

obj_ele = MysqlElephantV2()
obj_com = MysqlCompareV2()


def statr_type(comparetype):
	if comparetype == 0:
		tableName = 'elephant_v2.ele_task'
		suffix = ''
	elif comparetype == 1:
		tableName = 'elephant_v2.ele_task_panorama'
		suffix = '_panorama'
	elif comparetype == 2:
		tableName = 'elephant_v2.ele_task_veer'
		suffix = '_veer'
	
	data = {}
	data['tableName'] = tableName
	data['suffix'] = suffix
	return data


def check_is_complete(comparetype=0):
	data = statr_type(comparetype)
	tableName = data['tableName']
	suffix = data['suffix']
	sql_check = """select id,company_id,assign_spider from %s  where status=%s and `order`>=0  order by `order` ASC,is_priority DESC,add_time ASC""" % (
	tableName, 5)
	# print sql
	num = obj_ele.find(sql_check, 3)
	data = obj_ele.find(sql_check, 1)
	print num
	if num > 0:
		for line in data:
			task_id = line[0]
			company_id = line[1]
			assign_spider = line[2]
			sql = """select count(*)  from compare_v2.compare_%s where img_format < 3 and task_id=%s and run_times%s >= 2""" % (
			company_id, task_id, suffix)
			print sql
			task_num = obj_com.find(sql, 2)[0]
			print task_num
			# exit()
			sql2 = """select count(*)  from compare_v2.compare_%s where img_format < 3 and task_id=%s """ % (
			company_id, task_id)
			print sql2
			task_num_2 = obj_ele.find(sql2, 2)[0]
			print task_num_2
			nowTime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
			if task_num > 0 and task_num / task_num_2 > 0.99:
				sql_update = """update %s set status=6,compare_finsh_date='%s' where id=%s""" % (
				tableName, nowTime, task_id)
				print sql_update
				continue
			
			elif task_num == 0:
				sql_update = """update %s set status=7,compare_finsh_date='%s' where id=%s""" % (
				tableName, nowTime, task_id)
				
			else:
				continue
		time.sleep(60)
	
	
while True:
	for i in range(3):
		check_is_complete(i)
